﻿using System;
using System.Web;
using NSuggest.Jsonp.Core;

namespace NSuggest.Example.Hello
{
	/// <summary>
	/// An example of how to use JsonpEngine inside a IHttpHandler.
	/// </summary>
	public class HelloJsonpService : IHttpHandler
	{
		// Set a custom callback parameter name. 
		// Calls to the service: http://example.com/helloworld.json?cb=foo.
		// Return JSONP: [text/javascript] foo({"Message":"Hello world!"})
		readonly JsonpEngine _engine = new JsonpEngine(PerformQuery, callbackParameter: "cb");

		public void ProcessRequest(HttpContext context)
		{
			// (Optional) subscribe to events
			_engine.ErrorEvent += ((obj, e) => Console.WriteLine("An error occured. The HTTP status code was: " + e.HttpStatusCode) );
			_engine.SuccessEvent += ((obj, e) => Console.WriteLine("Great success occured, the message was: " + e.Result.Message));
			_engine.CompletedEvent += ((obj, e) => Console.WriteLine("It's all over"));

			// Handle context
			_engine.Execute(context);

		}

		public bool IsReusable
		{
			get { return true; }
		}

		public static dynamic PerformQuery(HttpContext context)
		{
			return new Hello() { Message = "Hello JSONP" };
		}
	}
}